package com.example.animalcase;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.example.animalcase.bean.Note;

import java.text.SimpleDateFormat;
import java.util.Date;

public class EditActivity extends AppCompatActivity {
    private Note note;
    private EditText etTitle,etContent;
    private Button editButton;
    private NoteDbOpenHelper mNoteDbOpenHelper;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_edit);

        etTitle=(EditText)findViewById(R.id.edit_title);
        etContent=(EditText)findViewById(R.id.edit_content);
        editButton=(Button)findViewById(R.id.edit_button);
        mNoteDbOpenHelper=new NoteDbOpenHelper(this);
        initData();

        editButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                save(v);
            }
        });
    }

    private void initData(){
        Intent intent=getIntent();
        note=(Note) intent.getSerializableExtra("note");
        if (note!=null){
            etTitle.setText(note.getTitle());
            etContent.setText(note.getContent());
        }
    }

    public void save(View view){
        String title=etTitle.getText().toString();
        String content=etContent.getText().toString();
        if (TextUtils.isEmpty(title)){
            Toast.makeText(this,"标题不能为空",Toast.LENGTH_SHORT).show();
            return;
        }
        note.setTitle(title);
        note.setContent(content);
        note.setCreatedTime(getTime());
        int row=mNoteDbOpenHelper.updateDate(note);
        if (row != -1){
            Toast.makeText(this,"修改成功",Toast.LENGTH_SHORT).show();
            this.finish();
        }else {
            Toast.makeText(this,"修改失败",Toast.LENGTH_SHORT).show();
        }
    }
    private String getTime(){
        SimpleDateFormat simpleDateFormat=new SimpleDateFormat("YYYY年MM月dd HH:mm:ss");
        Date date=new Date();
        return simpleDateFormat.format(date);

    }
}
